package com.mz.ozy.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.customview.widget.ViewDragHelper;

/**
 * Created by Chao on 2018-02-03.
 */

public class SlideView extends RelativeLayout {

    private View mView;
    private ViewDragHelper mDragHelper;

    public SlideView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initDragHelper();
    }

    private void initDragHelper() {
        mDragHelper = ViewDragHelper.create(this, new ViewDragHelper.Callback() {
            @Override
            public boolean tryCaptureView(View child, int pointerId) {
                return true;
            }

            @Override
            public int clampViewPositionHorizontal(View child, int left, int dx) {
                if (child.getLeft() + left <= 0) {
                    return 0;
                }
                return left;
            }

            // 解决ViewDragHelper中添加button，在控制button拖动的同时又不影响button的点击事件！
            @Override
            public int getViewHorizontalDragRange(View child) {
                return mView == child ? child.getWidth() : 0;
            }

            @Override
            public int getViewVerticalDragRange(View child) {
                return mView == child ? child.getHeight() : 0;
            }

            @Override
            public int clampViewPositionVertical(View child, int top, int dy) {
                return top;
            }

            @Override
            public void onViewReleased(View releasedChild, float xvel, float yvel) {
                super.onViewReleased(releasedChild, xvel, yvel);
                mDragHelper.settleCapturedViewAt(0, 0);
                invalidate();
            }
        });
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mDragHelper != null && mDragHelper.continueSettling(true)) {
            invalidate();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return mDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mDragHelper.processTouchEvent(event);
        return true;
    }

    public void setDragableView(View view) {
        mView = view;
    }

}